<template>
  <span>
    <a-input
      style="width: 100%"
      placeholder="请选择"
      v-model:value="selectNames"
    >
      <template v-slot:addonAfter>
        <a @click=";(organizeSelectVisible = true), (selectType = 0)">选择</a>
      </template>
    </a-input>
    <vxe-modal
      resize
      width="800"
      title="组织人员选择"
      v-model="organizeSelectVisible"
    >
      <a-card size="small" :bordered="false">
        <a-form layout="inline" :model="formInline">
          <a-form-item style="width:50%">
            <a-input
              v-model:value="formInline.serachText"
              placeholder="搜索条件"
            ></a-input>
          </a-form-item>

          <a-form-item>
            <a-button type="primary"><template #icon><ZoomInOutlined /></template>查询</a-button>
          </a-form-item>
        </a-form>
        <a-radio-group
          class="mt-1"
          name="radioGroup"
          @change="dataTypeChange"
          v-model:value="dataType"
        >
          <a-radio :value="0">组织架构</a-radio>
          <a-radio :value="1">工作组</a-radio>
        </a-radio-group>
        <a-transfer
          class="tree-transfer mt-1"
          :data-source="dataSource"
          :target-keys="targetKeys"
          :render="(item) => item.title"
          :show-select-all="false"
          @change="transferChange"
        >
          <template #children="{ direction, selectedKeys, onItemSelect }">
            <a-tree
              v-if="direction === 'left'"
              blockNode
              checkable
              checkStrictly
              defaultExpandAll
              :expandedKeys="expandedKeys"
              @expand="onExpand"
              :checkedKeys="[...selectedKeys, ...targetKeys]"
              :treeData="treeData"
              :load-data="onLoadData"
              :replaceFields="{ children: 'childs', title: 'name', key: 'id' }"
              @check="
                (_, props) => {
                  onChecked(
                    _,
                    props,
                    [...selectedKeys, ...targetKeys],
                    onItemSelect
                  )
                }
              "
              @select="
                (_, props) => {
                  onChecked(
                    _,
                    props,
                    [...selectedKeys, ...targetKeys],
                    onItemSelect
                  )
                }
              "
            />
          </template>
        </a-transfer>
        <div style="text-align: center">
          <a-divider></a-divider>
          <a-button type="primary" @click="submitUpdate"><template #icon><CheckSquareOutlined /></template>确定</a-button>
          <a-button class="ml-2" @click="closeModel"  ><template #icon><CloseCircleOutlined /></template>取消</a-button>
        </div>
      </a-card>
    </vxe-modal>
  </span>
</template>
<script>
  import { Gettreelist, Getnamesbyids } from '@/api/organize/api'
   import {
    ZoomInOutlined,
    CheckSquareOutlined,
    CloseCircleOutlined,
  } from '@ant-design/icons-vue'
  function isChecked(selectedKeys, eventKey) {
    return selectedKeys.indexOf(eventKey) !== -1
  }

  function handleTreeData(data, onlyUser, onlyOrganize, targetKeys = []) {
    data.forEach((item) => {
      item['disabled'] = targetKeys.includes(item.id)
      if (onlyUser === true) {
        if (item.type !== 4 && item.type !== 6) {
          item['disabled'] = true
        }
      }
      if (onlyOrganize === true) {
        if (item.type === 4 || item.type === 6) {
          item['disabled'] = true
        }
      }

      if (item.childs) {
        // console.log(item.childs, targetKeys)
        handleTreeData(item.childs, onlyUser, onlyOrganize, targetKeys)
      }
    })
    return data
  }

  export default {
    components:{
ZoomInOutlined,
    CheckSquareOutlined,
    CloseCircleOutlined,
    },
    data() {
      return {
        selectNames: '',
        organizeSelectVisible: false,
        formInline: {
          //搜索
          serachText: '',
        },
        targetKeys: [], // 穿梭组件已选择数据
        organizetreeData: [], // 树组件数据
        expandedKeys: [], // 已展开的树节点

        workorganizetreeData: [], // 工作组树组件数据
        treeorganizetreeData: [], // 组织、单位树组件数据

        dataSource: [], // 穿梭组件所有数据
        dataType: 0, // 0：组织架构1：工作组
      }
    },
    props: {
      // 只允许选择用户
      onlyUser: {
        type: Boolean,
        default: false,
      },

      initialData: {
        type: String,
        default: '',
      },
      onlyOrganize: {
        type: Boolean,
        default: false,
      },
    },
    watch: {
      initialData: function () {
        this.load()
      },
    },
    computed: {
      treeData() {
        return handleTreeData(
          this.organizetreeData,
          this.onlyUser,
          this.onlyOrganize,
          this.targetKeys
        )
      },
    },
    created() {
      var that = this
      if (this.organizetreeData.length === 0) {
        // 加载工作组数据
        Gettreelist({
          type: 1,
          isShowUser: true,
        }).then((res) => {
          if (res.isSuccess) {
            res.content.forEach((element) => {
              element.isLeaf = true
            })
            that.flatten(res.content)
            that.workorganizetreeData = res.content
          }
        })

        // 加载树控件组织架构初始数据
        Gettreelist({
          type: 0,
          isShowUser: true,
        }).then((res) => {
          if (res.isSuccess) {
            res.content[0].childs.forEach((element) => {
              element.isLeaf = !element.hasChilds
            })
            that.organizetreeData = res.content
            that.flatten(this.organizetreeData)
            that.expandedKeys = [res.content[0].id]
            that.treeorganizetreeData = res.content
          }
        })
      }
      this.load()
    },
    methods: {
      load() {
        if (this.initialData !== null) {
          Getnamesbyids({ ids: this.initialData }).then((res) => {
            console.log('res', res)
            if (res.isSuccess) {
              this.selectNames = ''
              // console.log(' res.content', res.content)
              if (res.content !== null) {
                res.content.forEach((element) => {
                  this.selectNames += element.name + ','
                  if (
                    this.targetKeys.find((targ) => targ === element.id) ===
                    undefined
                  ) {
                    this.targetKeys.push(element.id)
                    if (
                      this.dataSource.find((s) => s.key === element.id) ===
                      undefined
                    ) {
                      this.dataSource.push({
                        key: element.id,
                        title: element.name,
                        type: element.type,
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          this.selectNames = ''
        }
      },

      flatten(list = []) {
        list.forEach((item) => {
          this.dataSource.push({
            key: item.id,
            title: item.name,
            type: item.type,
          })

          if (item.childs !== null) {
            this.flatten(item.childs)
          }
        })
      },
      closeModel() {
        this.organizeSelectVisible = false
      },
      submitUpdate() {
        var res = {
          resId: '',
          resName: '',
          targetKeys: '',
        }
        console.log(res)
        const Fields = [...this.dataSource]
        res.targetKeys = this.targetKeys
        console.log(this.targetKeys)
        this.targetKeys.forEach((element) => {
          var item = Fields.find((s) => s.key === element)
          switch (item.type) {
            case 4:
              item.ids = 'u_' + item.key
              console.log(item.ids)

              break
            case 5:
              item.ids = 'w_' + item.key
              console.log(item.ids)

              break
            case 6:
              item.ids = 'p_' + item.key
              console.log(item.ids)

              break
            default:
              item.ids = item.key
              break
          }

          console.log(item.ids)
          res.resId += item.ids + ','
          res.resName += item.title + ','
        })
        res.resId = res.resId.substring(0, res.resId.length - 1)
        res.resName = res.resName.substring(0, res.resName.length - 1)
        this.selectNames = res.resName
        this.organizeSelectVisible = false
        this.$emit('childByValue', res)
      },

      // 数据来源类型改变
      dataTypeChange(e) {
        if (e.target.value === 1) {
          this.organizetreeData = this.workorganizetreeData
        } else {
          this.organizetreeData = this.treeorganizetreeData
        }
      },
      //穿梭框change事件
      transferChange(targetKeys) {
        this.targetKeys = targetKeys
      },
      onChecked(_, e, checkedKeys, itemSelect) {
        const { eventKey } = e.node
        itemSelect(eventKey, !isChecked(checkedKeys, eventKey))
      },

      // 树控件展开收缩事件
      onExpand(expandedKeys) {
        console.log(expandedKeys)
        // 用户点击展开时，取消自动展开效果
        this.expandedKeys = expandedKeys
      },
      //树控件异步加载
      onLoadData(treeNode) {
        return new Promise((resolve) => {
          if (treeNode.dataRef.childs) {
            console.log('抛出')
            resolve()
            return
          }
          setTimeout(() => {
            Gettreelist({
              type: this.dataType,
              isShowUser: true,
              parentId: treeNode.eventKey,
            }).then((res) => {
              if (res.isSuccess) {
                res.content[0].childs.forEach((element) => {
                  element.isLeaf = !element.hasChilds
                })
                treeNode.dataRef.childs = res.content[0].childs
                this.flatten(res.content[0].childs)
              }
            })

            resolve()
          }, 500)
        })
      },
    },
  }
</script>
<style scoped>
  .tree-transfer .ant-transfer-list:first-child {
    width: 50%;
    flex: none;
  }
</style>
